package com.alameda.test;

import cn.hutool.core.io.FileUtil;
import com.alameda.GuanChaoMediaJarApplication;
import com.alameda.common.commonpent.lock.api.DistributedLockTemplate;
import com.alameda.common.utils.CollectionUtils;
import com.alameda.common.utils.PubUtils;
import com.alameda.history.api.ApVideoHistoryProvider;
import com.alameda.media.dto.AdMediaDTO;
import com.alameda.media.vo.AdMediaVO;
import com.alameda.pojo.media.AdMediaDO;
import com.alameda.pojo.tag.AdTagDO;
import com.alameda.pojo.type.AdMediaTypeDO;
import com.alameda.service.media.AdMediaService;
import com.alameda.service.tag.AdTagService;
import com.alameda.service.type.AdMediaTypeService;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.List;
import java.util.Optional;

import static com.alameda.common.base.constant.MediaConstant.FileUpload.MAC_OS_FILE_INDEX_FORMAT;
import static com.alameda.common.base.constant.MediaConstant.StringConstant.EMPTY_STRING;

/**
 * 媒体文件处理脚本
 *
 * @author Lv
 * @date 2024/12/9
 */
@Slf4j
@SuppressWarnings("all")
@RunWith(SpringRunner.class)
@SpringBootTest(classes = GuanChaoMediaJarApplication.class)
public class MediaScript {

    @Autowired
    private AdMediaService adMediaService;

    @Autowired
    private DistributedLockTemplate distributedLockTemplate;

    /**
     * 本地文件批量上传方法
     */
    @Test
    public void testUploadBatch() {
        List<String> convertErrorList = CollectionUtils.newArrayList();
        List<String> uploadErrorList = CollectionUtils.newArrayList();
        List<String> successList = CollectionUtils.newArrayList();

        File file = new File("/Users/lv/Desktop/temp");
        File[] files = file.listFiles();
        for (int i = 0; i < files.length; i++) {
            File videoFile = files[i];

            if (MAC_OS_FILE_INDEX_FORMAT.equals(videoFile.getName()) || PubUtils.isNull(videoFile)) {
                continue;
            }

            long length = videoFile.length();

            log.info("当前上传文件:{} 文件大小:{}", videoFile.getName(), videoFile.length());

            MultipartFile multipartFile = null;
            try {
                multipartFile = convertToMultipartFile(videoFile.getPath());
            } catch (IOException e) {
                log.error("文件转换失败:{}", videoFile.getName(), e);
                convertErrorList.add(videoFile.getName());
                continue;
            }

            AdMediaDTO adMediaDTO = AdMediaDTO.builder().file(multipartFile).build();
            try {
                AdMediaVO adMediaVO = adMediaService.saveMedia(adMediaDTO);
                if (PubUtils.isNotNull(adMediaVO) && PubUtils.isNotEmpty(adMediaVO.getFileUrl())) {
                    successList.add(videoFile.getName());
                    FileUtil.del(videoFile);
                }
            } catch (Exception e) {
                log.error("文件上传失败:{}", videoFile.getName(), e);
                uploadErrorList.add(videoFile.getName());
            }
        }

        System.out.println("上传成功文件 " + successList);
        System.out.println("上传失败文件 " + uploadErrorList);
        System.out.println("转换失败文件 " + convertErrorList);
    }

    /**
     * 将本地文件转换为MultipartFile对象
     * 该方法主要用于将存储在本地路径中的文件转换为Spring框架中的MultipartFile对象，以便于文件上传等操作
     *
     * @param filePath 本地文件的路径
     * @return 转换后的MultipartFile对象
     * @throws IOException 如果读取文件时发生错误，则抛出IOException
     */
    private MultipartFile convertToMultipartFile(String filePath) throws IOException {
        File file = new File(filePath);
        FileInputStream fileInputStream = new FileInputStream(file);
        MultipartFile multipartFile = new MockMultipartFile("file", file.getName(), "text/plain", fileInputStream);
        fileInputStream.close();
        return multipartFile;
    }

    /**
     * 处理已删除数据
     */
    @Test
    public void testRemoveLogicDeletedFile() {
        Boolean aBoolean = adMediaService.removeLogicDeletedFile();
        System.out.println("处理结果:" + aBoolean);
    }

    @Autowired
    private AdTagService adTagService;

    @Autowired
    private AdMediaTypeService adMediaTypeService;

    @DubboReference
    private ApVideoHistoryProvider apVideoHistoryProvider;

    /**
     * 刷新文件路径
     */
    @Test
    public void reflushUrl() {
        String oldUrl = "http://192.168.0.103:9005";
        String newUrl = "http://192.168.0.101:9005";

        List<AdMediaDO> adMediaDOList = adMediaService.list();
        log.info("刷新前媒体文件信息:{}", JSONObject.toJSONString(adMediaDOList));

        adMediaDOList.forEach(adMediaDO -> {
            String fileUrl = adMediaDO.getFileUrl();
            String replaceUrl = fileUrl.replace(oldUrl, newUrl);
            adMediaDO.setFileUrl(replaceUrl);

            String fileCover = adMediaDO.getFileCover();
            String replaceCover = Optional.ofNullable(fileCover).orElse(EMPTY_STRING).replace(oldUrl, newUrl);
            adMediaDO.setFileCover(replaceCover);
        });

        log.info("刷新后媒体文件信息:{}", JSONObject.toJSONString(adMediaDOList));
        adMediaService.updateBatchById(adMediaDOList);

        List<AdTagDO> adTagDOList = adTagService.list();
        log.info("刷新前媒体标签信息:{}", JSONObject.toJSONString(adTagDOList));

        adTagDOList.forEach(item -> {
            String tagCoverUrl = item.getTagCoverUrl();
            String replace = Optional.ofNullable(tagCoverUrl).orElse(EMPTY_STRING).replace(oldUrl, newUrl);
            item.setTagCoverUrl(replace);
        });

        log.info("刷新后媒体标签信息:{}", JSONObject.toJSONString(adTagDOList));
        adTagService.updateBatchById(adTagDOList);

        List<AdMediaTypeDO> adMediaTypeDOList = adMediaTypeService.list();
        log.info("刷新前媒体分类信息:{}", JSONObject.toJSONString(adMediaTypeDOList));

        adMediaTypeDOList.forEach(item -> {
            String typeCoverUrl = item.getTypeCoverUrl();
            String replace = Optional.ofNullable(typeCoverUrl).orElse(EMPTY_STRING).replace(oldUrl, newUrl);
            item.setTypeCoverUrl(replace);
        });

        log.info("刷新后媒体分类信息:{}", JSONObject.toJSONString(adMediaTypeDOList));
        adMediaTypeService.updateBatchById(adMediaTypeDOList);

        /// List<ApVideoHistoryVO> apVideoHistoryVOList = apVideoHistoryProvider.loadApVideoHistory(ApVideoHistoryDTO.builder().build());
        /// log.info("刷新前历史记录信息:{}", JSONObject.toJSONString(apVideoHistoryVOList));
        /// apVideoHistoryVOList.forEach(item -> {
        ///     String videoCoverUrl = item.getVideoCover();
        ///     String replace = videoCoverUrl.replace(oldUrl, newUrl);
        ///     item.setVideoCover(replace);
        /// });
        /// List<ApVideoHistoryDTO> apVideoHistoryDTOList = ObjectUtils.convertList(apVideoHistoryVOList, ApVideoHistoryDTO.class);
        /// log.info("刷新后历史记录信息:{}", JSONObject.toJSONString(apVideoHistoryDTOList));
        /// apVideoHistoryProvider.updateMediaHistoryBatch(apVideoHistoryDTOList);
    }
}
